package org.lxy.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import com.baomidou.mybatisplus.extension.api.R;
import org.apache.catalina.startup.UserConfig;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.lxy.config.UserInfoConfig;
import org.lxy.core.exception.BusException;
import org.lxy.domain.*;
import org.lxy.domain.constant.CoreConstant;
import org.lxy.service.*;
import org.lxy.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

@Controller
@RequestMapping("/userinfo")
public class UserInfoController extends BaseController{
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private InfomationService infomationService;
    @Autowired
    private RecyclePointService recyclePointService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private RecycleGoodsService recycleGoodsService;

    @RequestMapping("login")
    public ModelAndView login(@Validated @NotNull String username, @Validated @NotNull String password, Boolean check, HttpServletResponse httpServletResponse) {
        ModelAndView modelAndView = new ModelAndView();
        boolean checks = Objects.nonNull(check) ? check : true;
        if (!checks){
            UserInfoEntity userInfo = getUserInfo(true);
            checks=Objects.isNull(userInfo);
        }
        List<UserInfoEntity> userInfoEntities = userInfoService.queryList(UserInfoEntity.builder().username(username).password(password).build());
        if (CollectionUtils.isNotEmpty(userInfoEntities) || !checks) {
            List<InfomationEntity> infomationEntities = infomationService.list();
            List<RecyclePointEntity> recyclePointEntities = recyclePointService.list();
            List<GoodsTypeEntity> goodsTypeEntities = goodsTypeService.list();
            HashMap<String, Integer> res = new HashMap<>();
            for (GoodsTypeEntity goodsTypeEntity : goodsTypeEntities) {
                List<RecycleGoodsEntity> recycleGoodsEntities = recycleGoodsService.queryList(RecycleGoodsEntity.builder().typeId(goodsTypeEntity.getId()).build());
                if (CollectionUtils.isNotEmpty(recycleGoodsEntities)) {
                    res.put(goodsTypeEntity.getName(), recycleGoodsEntities.size());
                }
            }
            List<RecycleGoodsEntity> entities = recycleGoodsService.queryList(RecycleGoodsEntity.builder().status("兑换中").build());
            modelAndView.addObject("entities", entities);
            modelAndView.addObject("types", res);
            modelAndView.addObject("infomationEntities", infomationEntities);
            modelAndView.addObject("recyclePointEntities", recyclePointEntities);
            modelAndView.setViewName("/jsp/Home");
            if (CoreConstant.ADMIN.equals(userInfoEntities.get(0).getRole())) {
                modelAndView.addObject("Account", userInfoEntities.get(0));
                modelAndView.setViewName("/jsp/index");
            }
            String s = UUID.randomUUID().toString();
            httpServletResponse.addCookie(new Cookie(CoreConstant.USER_COOKIE, s));
            UserInfoConfig.GLOBAL_USER_INFO.put(s, userInfoEntities.get(0));
        } else {
                throw new BusException("用户名或密码错误!", "/jsp/Login");
        }
        return modelAndView;
    }

    @RequestMapping("/operation")
    public ModelAndView operation(Long id, String op) {
        ModelAndView modelAndView = new ModelAndView();
        if (StringUtils.isNotBlank(op)) {
            if (CoreConstant.LIST.equals(op)) {
                List<UserInfoEntity> res = userInfoService.queryList(UserInfoEntity.builder().role("管理员").build());
                modelAndView.addObject("list", res);
                modelAndView.setViewName("/userinfo/userinfolist");
            } else if (CoreConstant.ADD.equals(op)) {
                modelAndView.addObject("entitys", UserInfoEntity.builder().build());
                modelAndView.setViewName("/userinfo/userinfoEdit");
            } else if (CoreConstant.EDIT.equals(op)) {
                UserInfoEntity entity = userInfoService.getById(id);
                modelAndView.addObject("entitys", entity);
                modelAndView.setViewName("/userinfo/userinfoEdit");
            }
        }
        return modelAndView;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(String ids) {
        return userInfoService.removeByIds(Arrays.asList(ids.split(","))) ? 1 : 0;
    }


    @RequestMapping("/edit")
    public void edit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        UserInfoEntity entity = new UserInfoEntity();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        entity.setId(Integer.parseInt(request.getParameter("id")));
        entity.setUsername(request.getParameter("username"));
        entity.setPassword(request.getParameter("password"));
        entity.setTelephone(request.getParameter("telephone"));
        entity.setRole("管理员");
        entity.setPoints(Integer.parseInt(request.getParameter("jifen")));
        boolean tag = false;
        if (entity.getId() > 0) {
            tag = userInfoService.updateById(entity);
        } else {
            tag = userInfoService.save(entity);
        }
        if (tag) {
            PrintWriter out = response.getWriter();
            out.write(
                    "<script>alert('操作成功!');window.parent.location.href='/userinfo/operation?op=List" + "';</script>");
        } else {
            PrintWriter out = response.getWriter();
            out.write("<script>alert('操作失败!');</script>");
            List<UserInfoEntity> list = userInfoService.list();
            request.setAttribute("plist", list);
            request.setAttribute("entitys", entity);
            request.getRequestDispatcher("/userinfo/userinfoEdit").forward(request, response);
        }
    }



    /*  *//**
     * 信息
     *//*
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		UserInfoEntity userInfo = userInfoService.getById(id);

        return R.ok().put("userInfo", userInfo);
    }

    *//**
     * 保存
     *//*
    @RequestMapping("/save")
    public R save(@RequestBody UserInfoEntity userInfo){
		userInfoService.save(userInfo);

        return R.ok();
    }

    *//**
     * 修改
     *//*
    @RequestMapping("/update")
    public R update(@RequestBody UserInfoEntity userInfo){
		userInfoService.updateById(userInfo);

        return R.ok();
    }

    *//**
     * 删除
     *//*
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		userInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }*/

}
